package com.webreport.dao.hibernate;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.orm.ObjectRetrievalFailureException;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;



import org.hibernate.transform.Transformers;

import com.webreport.dao.GenericDao;
import com.webreport.exception.DaoException;
import com.webreport.utils.DaoUtils;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;

public class GenericDaoHibernate<T, PK extends Serializable> implements GenericDao<T, PK> {
	protected final Log log = LogFactory.getLog(getClass());
	private Class<T> persistentClass;
	private HibernateTemplate hibernateTemplate;
	private SessionFactory sessionFactory;
	
	public GenericDaoHibernate(final Class<T> persistentClass) {
		this.persistentClass = persistentClass;
	}
	
	public GenericDaoHibernate(final Class<T> persistentClass, SessionFactory sessionFactory) {
		this.persistentClass = persistentClass;
		this.sessionFactory = sessionFactory;
		this.hibernateTemplate = new HibernateTemplate(sessionFactory);
	}
	
	public HibernateTemplate getHibernateTemplate() {
		return this.hibernateTemplate;
	}
	
	public SessionFactory getSessionFactory() {
		return this.sessionFactory;
	}
	
	@Autowired
	@Required
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
		this.hibernateTemplate = new HibernateTemplate(sessionFactory);
	}
	
	@SuppressWarnings("unchecked")
	public List<T> getAll() {
		StringBuffer hql = new StringBuffer();
		hql.append("from ").append(persistentClass.getName());
		return DaoUtils.queryHQL(hibernateTemplate, hql.toString());
	}
	
	public List<T> getAllDistinct() {
		Collection<T> result = new LinkedHashSet<T>(getAll());
		return new ArrayList<T>(result);
	}
	
	public T get(PK id) {
		T entity = (T) hibernateTemplate.get(this.persistentClass, id);
		return entity;
	}

	public boolean exists(PK id) {
		T entity = (T) hibernateTemplate.get(this.persistentClass, id);
		return entity != null;
	}

	public PK insert(T object) throws DaoException {
		return (PK) hibernateTemplate.save(object);
	}

	public T update(T object) throws DaoException {
		return hibernateTemplate.merge(object);
	}
	
	
}
